package com.school_admin.service.impl;

import com.school_admin.config.Result;
import com.school_admin.entity.Comment;
import com.school_admin.mapper.CommentMapper;
import com.school_admin.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2024-03-18
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    private  CommentMapper commentMapper;

    @Override
    public Result<?> getCommentByPostId(String postId) {
        List<Map> list = commentMapper.getCommentByPostId(postId);
        List<Map> resultMap = new ArrayList<>();
        for (Map map : list) {
            String level = map.get("level").toString();
            if ("0".equals(level)) {
                map.put("children", new ArrayList<>());
                resultMap.add(map);
            }
        }
        /** 第二次循环，将不是根节点 根据root_id(根节点id)归类 **/
        for (Map map : list){
            if (!("0".equals(map.get("level").toString()))) {
                /**
                 * 不是根节点的数据，对根节点数据进行遍历，
                 * 然后跟非根节点数据的rootId进行匹配，符合添加到该child节点中
                 * */
                for (Map rootMap : resultMap) {
                    if (rootMap.get("id").equals(map.get("rootId"))) {
                        List<Map> children = (List<Map>) rootMap.get("children");
                        children.add(map);
                        break;
                    }
                }
            }
        }
        return Result.success(resultMap);
    }

    @Override
    public Result<?> getCommentList(int page, int pageSize) {
        int start =  (page - 1) * pageSize;
        List<Map> list = commentMapper.getCommentList(start,pageSize);
        if (list.size() > 0) {
            Map map = new HashMap<>();
            map.put("list",list);
            map.put("total",commentMapper.getCommentCount());
            return Result.success(map);
        }
        return  Result.fail("评论列表为空");
    }

    @Override
    public Result<?> getCommentListByKewWord(int page, int pageSize, String keyWord) {
        int start =  (page - 1) * pageSize;
        List<Map> list = commentMapper.getCommentListByKewWord(start,pageSize,keyWord);
        if (list.size() > 0) {
            Map map = new HashMap<>();
            map.put("list",list);
            map.put("total",commentMapper.getCommentCountByKewWord(keyWord));
            return Result.success(map);
        }
        return  Result.fail("搜索评论列表为空");
    }
}
